<template>
  <PageWrapper title="权限配置" contentFullHeight contentClass="flex">
    <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
    <div class="flex-1">
      <a-row :gutter="16">
        <a-col span="6">
          <BasicTable @register="registerTable">
            <!-- <template #toolbar>
              <a-button type="default" @click="handleCreate">添加</a-button>
              <a-button type="primary" v-if="!isEdit" @click="triggerRelation">关联设置</a-button>
              <a-button type="default" v-if="isEdit" @click="isEdit = false">取消</a-button>
              <a-button type="primary" v-if="isEdit" @click="save">保存</a-button>
            </template> -->
            <template #name="{ record }">
              <a @click="titleClick($event, record)">{{ record.name }}</a>
            </template>
          </BasicTable>
        </a-col>
        <a-col span="18" v-if="list.length">
          <div class="com-bg p-2 mb-2 text-right">
            <a-button type="primary" v-auth="['10072', RoleEnum.SUPER]" @click="save"
              >保存</a-button
            >
          </div>
          <div class="com-bg p-4 pt-2">
            <template v-for="(item, index) in list" :key="item.id">
              <div
                :style="{
                  borderBottom: '1px solid rgba(41, 41, 41, .1)',
                  marginTop: index === 0 ? '16px' : '40px',
                  paddingBottom: '8px',
                }"
              >
                <a-checkbox
                  v-model:checked="item.checked"
                  :indeterminate="item.indeterminate"
                  @change="onCheckAllChange(item.checked, item)"
                >
                  {{ item.name }}
                </a-checkbox>
              </div>
              <br />
              <a-checkbox-group
                @change="onItemChange(item.children_value, item)"
                v-model:value="item.children_value"
                :options="item.children"
              />
            </template>
          </div>
        </a-col>
      </a-row>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, toRefs } from 'vue';

  import { BasicTable, useTable } from '/@/components/Table';
  import {
    deleteRole,
    getRoleList,
    getFunCodes,
    getRoleFunCodes,
    editRoleFunCodes,
  } from '/@/api/sys/user';
  import { PageWrapper } from '/@/components/Page';
  // import DeptTree from './DeptTree.vue';

  import { useModal } from '/@/components/Modal';

  import { columns } from './role.data';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { Checkbox, Col, message, Row } from 'ant-design-vue';
  import { cloneDeep, groupBy } from 'lodash';
  import { RoleEnum } from '/@/enums/roleEnum';

  export default defineComponent({
    name: 'Auth',
    components: {
      BasicTable,
      'a-checkbox': Checkbox,
      'a-checkbox-group': Checkbox.Group,
      PageWrapper,
      'a-row': Row,
      'a-col': Col,
    },
    setup() {
      const funList = reactive<{ list: any[] }>({
        list: [],
      });
      let roleId = 0;
      let flatCodes: any[] = [];
      getFunCodes().then((res) => {
        flatCodes = cloneDeep(res);
        loopCodeData(res);
        if (roleId) {
          updateRelation(res);
        }
      });

      // 监听不到对象数组里的属性变化
      // watch(
      //   () => funList.list,
      //   (val) => {
      //     console.log(val);
      //     val.forEach((elem) => {
      //       elem.checked = elem.children_value.length === elem.children.length;
      //       elem.indeterminate =
      //         !!elem.children_value.length && elem.children_value.length < elem.children.length;
      //     });
      //     // state.indeterminate = !!val.length && val.length < plainOptions.length;
      //     // state.checkAll = val.length === plainOptions.length;
      //   },
      // );

      function loopCodeData(res) {
        const dataGroup = groupBy(res, 'p_id');
        console.log(dataGroup);
        if (dataGroup['-1']) {
          funList.list = dataGroup['-1'].map((v) => {
            let rv = {
              ...v,
              children_value: dataGroup[v.id]
                ? dataGroup[v.id].filter((cv) => cv.checked).map((cv2) => cv2.code)
                : [],
              checked: false,
              indeterminate: false,
              children: dataGroup[v.id]
                ? dataGroup[v.id].map((c) => {
                    return {
                      ...c,
                      label: c.name,
                      value: c.code,
                    };
                  })
                : [],
            };
            rv.checked = rv.children_value.length === rv.children.length;
            rv.indeterminate =
              rv.children_value.length !== 0 && rv.children_value.length !== rv.children.length;
            return rv;
          });
        }
      }

      const [registerModal, { openModal }] = useModal();

      const userStore = useUserStoreWithOut();
      const [registerTable, { reload, setSelectedRowKeys }] = useTable({
        // title: '账号列表',
        api: getRoleList,
        columns,
        searchInfo: {
          pid: userStore.getUserInfo.id,
        },
        clickToRowSelect: true,
        indexColumnProps: {
          width: 80,
        },
        rowSelection: {
          type: 'radio',
          onChange: updateRelation,
        },
        rowKey: 'id',
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        afterFetch: (res) => {
          setTimeout(() => {
            if (res && res[0]) {
              setSelectedRowKeys([res[0].id]);
            }
          }, 100);
          return res;
        },
      });

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        deleteRole(record.id).then(
          () => {
            // msg
            handleSuccess();
          },
          () => {},
        );
      }

      function handleSuccess() {
        reload();
      }

      async function updateRelation(rows?) {
        rows = rows || [0];
        roleId = rows[0] || roleId;
        if (roleId) {
          const res = await getRoleFunCodes(roleId);
          if (res) {
            restoreFunList();
            fillRoleCode(res);
            // console.log(res);
            // res.forEach((v) => {
            //   if (v.type === 2) {
            //     gs.push(parseInt(v.number));
            //   } else {
            //     cs.push(v.number);
            //   }
            // });
          }
        }
      }

      function restoreFunList() {
        funList.list.forEach((v) => {
          v.indeterminate = false;
          v.checked = false;
          v.children_value = [];
        });
      }

      function fillRoleCode(codes: string[]) {
        let deepCodes = flatCodes.map((v) => {
          if (codes.includes(v.code)) {
            return {
              ...v,
              checked: true,
            };
          } else {
            return v;
          }
        });

        loopCodeData(deepCodes);
        // funList.list.forEach((v) => {});
      }

      const onCheckAllChange = (e: any, item: any) => {
        console.log(e, item);
        if (e) {
          item.children_value = item.children.map((v) => v.code);
        } else {
          item.children_value = [];
        }
        item.indeterminate = false;
        // Object.assign(state, {
        //   checkedList: e.target.checked ? plainOptions : [],
        //   indeterminate: false,
        // });
      };
      const onItemChange = (e: any, item: any) => {
        console.log(e, item);
        if (e.length && e.length !== item.children.length) {
          item.indeterminate = true;
          item.checked = false;
        } else if (e.length && e.length === item.children.length) {
          item.indeterminate = false;
          item.checked = true;
        } else {
          item.indeterminate = false;
          item.checked = false;
        }
        // Object.assign(state, {
        //   checkedList: e.target.checked ? plainOptions : [],
        //   indeterminate: false,
        // });
      };

      function save() {
        let codes: string[] = [];
        console.log(funList.list);
        funList.list.forEach((e) => {
          if (e.indeterminate || e.checked) {
            codes.push(e.code);
            codes.push(...e.children_value);
          }
        });
        editRoleFunCodes(roleId, codes).then(() => {
          message.success('保存角色权限成功！');
        });
      }

      return {
        registerTable,
        registerModal,

        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        ...toRefs(funList),
        onCheckAllChange,
        onItemChange,
        save,
        RoleEnum,
      };
    },
  });
</script>
